package com.GLM.Viewer.Party;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.GLM.Constants.Constant;
import com.GLM.Entity.StoreEntivity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.RefreshListView.XListView;
import com.GLM.Tools.Utils.RefreshListView.XListView.IXListViewListener;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Map.MapMainActivity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class CreateNewPartyLocationActivity extends Activity implements IXListViewListener {
	private final static int STORELIST_LOADING = 111;
	private final static int STORELIST_LOADED = 222;
	
	Animation mAnimIn;
	Animation mAnimOut;
	
	View mInputFieldOneLine;
	TextView mInputFieldOneLineTextView;
	EditText mInputFieldOneLineEditText;
	InputMethodManager imm;
	
	private Button gobackButton;
	private Button searchButton;
	private Button classButton;
	private ProgressBar mProgressBar;
	private XListView mXListView;
	private int mUserId;
	private int reqWay = 1;
	private List<Map<String, Object>> storeListItems = new ArrayList<Map<String, Object>>();
	private String[] storeItemKeys = new String[] { "mgName", "mgAddress", "mgNear" };
	private int[] storeItemViews = new int[] { R.id.party_meeting_storename, R.id.party_meeting_addressname, R.id.party_meeting_near };
	private Map<String, String> storePic = new HashMap<String, String>();
	int page = 1;
	private SimpleAdapter mStoreAdapter;
	private List<StoreEntivity> mEntivities = new ArrayList<StoreEntivity>();
	private AsynImageLoader imageLoader = new AsynImageLoader();
	private LinearLayout typelayout;
	private double lati;
	private double longi;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case STORELIST_LOADING:
				page = 1;
				storeListItems.clear();
				mXListView.setAdapter(null);
				thread = new Thread(new Runnable() {

					public void run() {
						// TODO Auto-generated method stub
						mProgressBar.setVisibility(View.VISIBLE);
						initLocationList(reqWay);
						mStoreAdapter = new SimpleAdapter(CreateNewPartyLocationActivity.this, storeListItems, R.layout.view_newparty_location_listitem, storeItemKeys, storeItemViews);
						mHandler.sendEmptyMessage(STORELIST_LOADED);
					}
				});
				thread.start();
				break;
			case STORELIST_LOADED:
				mProgressBar.setVisibility(View.INVISIBLE);
				mXListView.setAdapter(mStoreAdapter);
				onLoad();
				bindItemClick();

				break;

			default:
				break;
			}
		};
	};

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_newparty_location);

		mUserId = UserInfoDAO.getUserInfo(this).getUserId();
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		initInputFields();
		initAnimation();
		initViews();
		
		mXListView = (XListView) findViewById(R.id.newparty_location_listview);
		mXListView.setPullLoadEnable(true);
		mXListView.setXListViewListener(this);
		initRegisterInputFieldButton();
		mHandler.sendEmptyMessage(STORELIST_LOADING);
	}

	private void initInputFields() {
		mInputFieldOneLine = findViewById(R.id.inputfield_oneline);
		mInputFieldOneLine.setVisibility(View.GONE);
		mInputFieldOneLineTextView = (TextView) findViewById(R.id.inputfield_title);
		mInputFieldOneLineEditText = (EditText) findViewById(R.id.inputfield_edittext);

	}
	
	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}
	
	
	private void showOneLineInputField() {
		mInputFieldOneLine.startAnimation(mAnimIn);
		mInputFieldOneLine.setVisibility(View.VISIBLE);
		mInputFieldOneLineEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	private void hideOneLineInputField() {
		mInputFieldOneLineEditText.setText("");
		mInputFieldOneLineEditText.setInputType(InputType.TYPE_NULL);
		mInputFieldOneLineEditText.clearFocus();
		mInputFieldOneLine.startAnimation(mAnimOut);
		mInputFieldOneLine.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		
	}
	
	
	private void initRegisterInputFieldButton() {
		// one line
		Button inputCancelButton = (Button) findViewById(R.id.inputfield_cancelbutton);
		inputCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideOneLineInputField();
			}
		});

		Button inputOkButton = (Button) findViewById(R.id.inputfield_okbutton);
		inputOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String searchText = mInputFieldOneLineEditText.getText().toString().trim();
				if(!searchText.equals("")){
					hideOneLineInputField();
					initSearchPlace(searchText);
				}
			}
		});
	}
	
	public void initViews() {
		gobackButton = (Button) findViewById(R.id.goback_newparty_location_Button);
		searchButton = (Button) findViewById(R.id.newparty_location_search_button);
		gobackButton.setOnClickListener(onClickListeners);
		searchButton.setOnClickListener(onClickListeners);
		classButton = (Button) findViewById(R.id.newparty_location_infotip);
		classButton.setOnClickListener(onClickListeners);
		mProgressBar = (ProgressBar) findViewById(R.id.newparty_location_probar);
	    Button goMapBtn = (Button)findViewById(R.id.newparty_location_mapbtn);
	    goMapBtn.setOnClickListener(onClickListeners);
	}

	private OnScrollListener scrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {

		}

		public void onScroll(AbsListView v, int firstVisibleItem, int visibleCount, int totalItemCount) {
			if (visibleCount > 0 && totalItemCount > 0) {
				loadPics();
			}
		}
	};

	
	private void onLoad() {
		mXListView.stopRefresh();
		mXListView.stopLoadMore();
		mXListView.setRefreshTime("刚刚");
	}

	public void initSearchPlace(String searchText){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			page = 1;
			jsonData.put("mg_page", page);
			jsonData.put("mg_name", searchText);
			jsonData.put("user_id", mUserId);
			
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_SEARCHSTORE, jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if(status == Constant.RESP_STATUS_SUCCESS){
					JSONArray jsonArray = data.getJSONArray("mgData");
					storeListItems.clear();
					storePic.clear();
					mEntivities.clear();
					initLocationPlaceFromJson(jsonArray);
				}
				
						
			}
		} catch (Exception e) {
			// TODO: handle exception
			
			e.printStackTrace();
		}
	}
	
	protected void loadPics() {
		int count = mXListView.getChildCount();

		for (int i = 0; i < count; i++) {
			View view = mXListView.getChildAt(i);
			TextView textview = (TextView) view.findViewById(R.id.party_meeting_storename);
			if (textview == null)
				continue;
			String key = textview.getText().toString();
			ImageView imageview = (ImageView) view.findViewById(R.id.party_meeting_storepic);
			String url = storePic.get(key);
			if (url != null && !url.equals("")) {
				Log.d("URL", url);
				imageLoader.showImageAsyn(imageview, Constant.URL_MSGGROUP_SMALL + url, R.drawable.glm_background);
			} else {
				imageview.setBackgroundColor(Color.WHITE);
			}

		}
		mXListView.invalidate();

	}

	public void initLocationList(int ordey_way) {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put("mg_page", page);
			jsonData.put("order_way", ordey_way);
			jsonData.put("user_id", mUserId);
			if (ordey_way == 2) {
				jsonData.put("user_long", longi);
				jsonData.put("user_lati", lati);
			}
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETSTOREINFOS, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray("msgGroupData");
					initLocationPlaceFromJson(jsonArray);
				} else {
					ViewsUtil.showErrorTip(CreateNewPartyLocationActivity.this, R.string.global_error_networkerr);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

			e.printStackTrace();
		}
	}

	public void initLocationPlaceFromJson(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			StoreEntivity entivity = gson.fromJson(jsonArray.getString(i).toString(), StoreEntivity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			String mgName = entivity.getMg_name();
			String mgAddress = entivity.getMg_address();
			item.put("mgName", mgName);
			item.put("mgAddress", mgAddress);
			if (entivity.getMg_juli() != 0)
				item.put("mgNear", (int) entivity.getMg_juli() + "m");
			else
				item.put("mgNear", "");
			storeListItems.add(item);
			storePic.put(mgName, entivity.getMg_picture());
			mEntivities.add(entivity);
		}

	}

	public void bindItemClick() {
		mXListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
				// TODO Auto-generated method stub
				StoreEntivity mEntivity = mEntivities.get((int) id);
				Intent intent = new Intent(CreateNewPartyLocationActivity.this, PartyStoreDetailActivity.class);
				intent.putExtra("store", mEntivity);
				intent.putExtra("ParentActivity", "CreateNewPartyLocationActivity");
				startActivity(intent);

			}

		});

		mXListView.setOnScrollListener(scrollListener);
	}

	OnClickListener onClickListeners = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			switch (v.getId()) {
			case R.id.goback_newparty_location_Button:
				NavUtils.navigateUpTo(CreateNewPartyLocationActivity.this, new Intent(CreateNewPartyLocationActivity.this, CreateNewPartyViewActivity.class));
				break;
			case R.id.newparty_location_search_button:
				showOneLineInputField();
				break;
			case R.id.newparty_location_mapbtn:
				Intent mapIntent = new Intent(CreateNewPartyLocationActivity.this,MapMainActivity.class);
				startActivity(mapIntent);
				break;
			case R.id.newparty_location_infotip:
				typelayout = (LinearLayout) findViewById(R.id.newparty_class_layout);
				if (typelayout.getVisibility() == View.VISIBLE) {
					typelayout.setVisibility(View.INVISIBLE);
				} else {
					typelayout.setVisibility(View.VISIBLE);
				}
				Button likesBtn = (Button) typelayout.findViewById(R.id.newparty_class_likes);
				Button nearBtn = (Button) typelayout.findViewById(R.id.newparty_class_near);
				Button confirmBtn = (Button) typelayout.findViewById(R.id.newparty_class_confirm);
				Button joinCountBtn = (Button) typelayout.findViewById(R.id.newparty_class_partycount);
				likesBtn.setOnClickListener(onClickListeners);
				nearBtn.setOnClickListener(onClickListeners);
				confirmBtn.setOnClickListener(onClickListeners);
				joinCountBtn.setOnClickListener(onClickListeners);
				break;
			case R.id.newparty_class_likes:
				typelayout.setVisibility(View.INVISIBLE);
				classButton.setText(getString(R.string.newparty_tips_location_likesort));
				typeRefresh(1);
				break;
			case R.id.newparty_class_near:
				typelayout.setVisibility(View.INVISIBLE);
				Intent locintent = new Intent(CreateNewPartyLocationActivity.this,MapMainActivity.class);
				locintent.putExtra("ActivityIntent", "getData");
				startActivityForResult(locintent, Constant.PARTY_STORE_LOCATE_CODE);
				
				break;
			case R.id.newparty_class_confirm:
				typelayout.setVisibility(View.INVISIBLE);
				classButton.setText(getString(R.string.newparty_tips_location_confirm));
				typeRefresh(3);
				break;
			case R.id.newparty_class_partycount:
				typelayout.setVisibility(View.INVISIBLE);
				classButton.setText(getString(R.string.newparty_tips_location_partycount));
				typeRefresh(4);
				break;
			}
		}
	};

	public void typeRefresh(int newreqway) {
		typelayout.setVisibility(View.INVISIBLE);
		page = 1;
		reqWay = newreqway;
		mEntivities.clear();
		storeListItems.clear();
		mXListView.setAdapter(null);
		mProgressBar.setVisibility(View.VISIBLE);
		mHandler.post(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				initLocationList(reqWay);
				mProgressBar.setVisibility(View.INVISIBLE);
				mStoreAdapter = new SimpleAdapter(CreateNewPartyLocationActivity.this, storeListItems, R.layout.view_party_meetingplace_listitem, storeItemKeys, storeItemViews);
				mXListView.setAdapter(mStoreAdapter);
				onLoad();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case Constant.PARTY_STORE_LOCATE_CODE:
				classButton.setText(getString(R.string.newparty_tips_location_farnear));
				Bundle bundle = data.getExtras();
				if(bundle != null){
					lati = bundle.getDouble("lati");
					longi = bundle.getDouble("longi");
				}
				typeRefresh(2);
				break;

			default:
				break;
			}
		}
	}
	
	public void onRefresh() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			public void run() {
				page = 1;
				storeListItems.clear();
				mEntivities.clear();
				initLocationList(reqWay);
				mStoreAdapter = new SimpleAdapter(CreateNewPartyLocationActivity.this, storeListItems, R.layout.view_party_meetingplace_listitem, storeItemKeys, storeItemViews);
				mXListView.setAdapter(mStoreAdapter);
				onLoad();
			}
		}, 2000);
	}

	public void onLoadMore() {
		// TODO Auto-generated method stub
		page += 1;
		mHandler.postDelayed(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				initLocationList(reqWay);
				mStoreAdapter.notifyDataSetChanged();
				onLoad();
			}
		}, 2000);
	}

}
